﻿@page "/editpages"
@attribute [TabItemOption(Text = "页面编辑")]
@using System.Diagnostics.CodeAnalysis

<PageTitle>页面编辑</PageTitle>

<div class="row">
    <div class="col-6 col-sm-6">
        <Select TValue="string" Color="Color.Primary" Items="GroupItems()" OnSelectedItemChanged="OnItemChanged">
        </Select>
    </div>
    <div class="col-2 col-sm-2">
        <Button Text="保存" OnClickWithoutRender="Save" Color="Color.Primary" />
    </div>
</div>

@if (TpvPage != null)
{
    <div class="row">
        <h5 class="m-3">页面说明</h5>
        <div style="width: 100%; height: 500px;">

            <Markdown Height="500" MinHeight="300" PreviewStyle="PreviewStyle.Tab" InitialEditType="InitialEditType.Wysiwyg" Language="@Language" @bind-Value="@TpvPage.Markdown" @bind-Html="@TpvPage.Html" />
        </div>
    </div>
}

@code {

    /// <summary>
    /// 获取并设置Markdown语言
    /// </summary>
    private string? Language { get; set; }

    [Inject]
    [NotNull]
    private ToastService? ToastService { get; set; }


    /// <summary>
    /// 注入fsql服务
    /// </summary>
    [Inject]
    [NotNull]
    IFreeSql? fsql { get; set; }

    [NotNull]
    List<WebPages>? Items { get; set; } = new List<WebPages>();

    [NotNull]
    WebPages? TpvPage { get; set; }

    protected override void OnInitialized()
    {
        Language = CultureInfo.CurrentUICulture.Name;
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            //读取页面数据,显示第一页到编辑器
            Items = fsql.Select<WebPages>().OrderBy(a => a.Code).ToList();
            TpvPage = Items?.First();
            StateHasChanged();
        }
    }

    Task Save()
    {
        var res = fsql.Update<WebPages>().SetSource(TpvPage).ExecuteAffrows();
        if (res > 0)
        {
            ToastService.Success("保存成功");
        }
        return Task.CompletedTask;
    }

    /// <summary>
    /// Select 组件数据源
    /// </summary>
    /// <returns></returns>
    private IEnumerable<SelectedItem> GroupItems()
    {
        if (Items == null)
        {
            return new List<SelectedItem>();
        }
        var list = new List<SelectedItem>();
        foreach (var item in Items)
        {
            list.Add(new SelectedItem() { Value = item.Code ?? "", Text = item.PageName ?? "", GroupName = item.ParentCode ?? "" });
        }
        return list;
    }

    /// <summary>
    /// 下拉选项改变时调用此方法
    /// </summary>
    /// <param name="item"></param>
    private Task OnItemChanged(SelectedItem item)
    {
        TpvPage = Items.Where(a => a.Code == item.Value).First();
        System.Console.WriteLine($"SelectedItem Text: {item.Text} Value: {item.Value} Selected");
        StateHasChanged();
        return Task.CompletedTask;
    }
}
